#Python's memory I/O
File I/O operates on the hard disk (external storage). Often, you need to store and manipulate data in memory (e.g., dynamically generated images or compressed archives on web pages). In Python, this can be done using StringIO
and BytesIO
.
Variables themselves operate in memory;
StringIO
andBytesIO
provide file-like, convenient stream interfaces for memory I/O operations.
#StringIO
StringIO
is for I/O operations on strings. Like file I/O, it supports read
, write
, tell
, seek
, etc. You can get the entire string using the getvalue
method.
import io
from io import StringIO
stream = StringIO("甲乙丙丁戊己庚辛壬癸") # Create a StringIO object
print("Initial offset:", stream.tell()) # Check initial offset
print(stream.read(3)) # Read 3 characters
stream.seek(6, io.SEEK_SET) # Set offset to 6 characters from start
print(stream.read(3)) # Read 3 characters
stream.seek(0, io.SEEK_SET) # Set offset to start
stream.write("ABC") # Write (overwrite) in the middle
print(stream.getvalue()) # Get the entire string
#BytesIO
BytesIO
is for I/O operations on byte data. Like file I/O, it supports read
, write
, tell
, seek
, etc. You can get the entire bytes content using the getvalue
method.
import io
from io import BytesIO
stream = BytesIO(b"ABCDEFGHIJKLMNOPQRSTUVWXYZ") # Create a BytesIO object
print("Initial offset:", stream.tell()) # Check initial offset
print(stream.read(3)) # Read 3 bytes
stream.seek(6, io.SEEK_SET) # Set offset to 6 bytes from start
print(stream.read(3)) # Read 3 bytes
stream.seek(0, io.SEEK_SET) # Set offset to start
stream.write(b"XXX") # Write (overwrite) in the middle
print(stream.getvalue()) # Get the entire bytes content